package ip.command;

import ip.ejb.session.facade.CountryFacadeLocal;
import ip.ejb.session.facade.CountryFacadeLocalHome;
import ip.exceptions.UnexpectedException;
import ip.util.EJBHomeFactory;

import java.util.Collection;

import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.RemoveException;
import javax.naming.NamingException;

import org.apache.log4j.Logger;

public class GetCountriesCommand extends Command{

	private Collection countries;
	private CountryFacadeLocal countryFacadeLocal;
	private Logger logger = Logger.getLogger(this.getClass());

	public void init() throws UnexpectedException{
		try {
			logger.debug("init()");
			CountryFacadeLocalHome countryFacadeLocalHome = (CountryFacadeLocalHome) EJBHomeFactory.getInstance().createLocalHome(ip.ejb.session.facade.CountryFacadeLocalHome.class);
			countryFacadeLocal = countryFacadeLocalHome.create();
		} catch (NamingException e) {
			logger.error(e);
			e.printStackTrace();
			throw new UnexpectedException();			
		} catch (CreateException e) {
			logger.error(e);
			e.printStackTrace();
			throw new UnexpectedException();
		}

	}
	public void execute() throws UnexpectedException{
		try{
			logger.debug("execute()");
			countries = countryFacadeLocal.getAllCountries();
			logger.debug("execute() - countries: "+countries.size());
		}
		catch (Exception e) {
			logger.error(e);
			throw new UnexpectedException();
		}
	}

	public void dispose() throws UnexpectedException{
		try {
			logger.debug("dispose()");
			countryFacadeLocal.remove();
		} catch (EJBException e) {
			logger.error(e);
			e.printStackTrace();
			throw new UnexpectedException();
		} catch (RemoveException e) {
			logger.error(e);
			e.printStackTrace();
			throw new UnexpectedException();
		}
	}

	public Collection getCountries() {
		return countries;
	}

}
